//
//  XCBluetoothMessageManager.swift
//  RXSwiftDemo1
//
//  Created by mac on 2025/3/6.
//

import Foundation
import CoreBluetooth
import RxSwift

class XCBluetoothMessageManager {
    static let instance = XCBluetoothMessageManager()
    private let disposeBag = DisposeBag()
    private lazy var blueManager = XCBluetoothManager.instance
    private init() {}
    
    
    
    // 下发时间
    func sendTimeToDevice() ->Observable<Void> {
        let formatStringForHours = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)
        let is12 = formatStringForHours?.contains("a") ?? false
        let offset = TimeZone.current.secondsFromGMT()

        let timeString = String(format: "P01,%@,%d,%d,%.1f", getDateWithFormatterString(formatter: "yyyyMMddHHmmssSSS"), is12 ? 1 : 0, 1, Double(offset) / 3600.0)
        print("发送数据：\(timeString)")
        if let data = timeString.data(using: .utf8) {
            return blueManager.writeValue(data, type: .withoutResponse)
                
        }
        return Observable.empty()
    }
    
    // 获取设备电量
    func getDeviceElectricity() ->Observable<Void> {
        
        let eleStr = String(format: "P02,%@",getDateWithFormatterString(formatter: "yyyyMMddHHmmssSSS"))
        print("发送数据：\(eleStr)")
        
        if let data = eleStr.data(using: .utf8) {
            return blueManager.writeValue(data, type: .withoutResponse)
        }
        return Observable.empty()
    }
    
    //获取消息
    func readBluetoothMsg() -> Observable<Data> {
        return blueManager.readValue()
    }
}

extension XCBluetoothMessageManager {
    func getDateWithFormatterString(formatter: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = formatter.isEmpty ? "yyyyMMddHHmmss" : formatter
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.calendar = Calendar(identifier: .gregorian)
        return dateFormatter.string(from: Date())
    }
}

